package com.zhong.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhong.common.annotation.DataScope;
import com.zhong.common.constant.UserConstants;
import com.zhong.common.core.domain.entity.SysRole;
import com.zhong.common.core.domain.entity.SysUser;
import com.zhong.common.exception.ServiceException;
import com.zhong.common.utils.SecurityUtils;
import com.zhong.common.utils.StringUtils;
import com.zhong.common.utils.WrapperUtils;
import com.zhong.common.utils.bean.BeanValidators;
import com.zhong.common.utils.spring.SpringUtils;
import com.zhong.system.domain.SysPost;
import com.zhong.system.domain.SysUserPost;
import com.zhong.system.domain.SysUserRole;
import com.zhong.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author zhongzc
 */
@Service
@RequiredArgsConstructor
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser>
{
    private final SysConfigService configService;

    private final Validator validator;

    private final SysUserRoleService userRoleService;

    private final SysUserPostService userPostService;

    private final SysDeptService deptService;

    private final SysRoleService roleService;

    private final SysPostService postService;

    public Page<SysUser> findPage(SysUser user){
        Page<SysUser> p = page(user.getPage(),WrapperUtils.getLambdaQueryWrapper(user));
        if(p.getTotal()>0){
            for(SysUser u:p.getRecords()){
                if(StringUtils.isNotEmpty(u.getDeptId())){
                    u.setDept(deptService.getById(u.getDeptId()));
                }
            }
        }
        return p;
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        return list(WrapperUtils.getLambdaQueryWrapper(user).orderByDesc(SysUser::getCreateTime));
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<SysUser> selectAllocatedList(SysUser user)
    {
        List<String> userIdList = userRoleService.findListByRoleId(user.getRoleId()).stream().map(SysUserRole::getUserId).collect(Collectors.toList());
        if(userIdList.isEmpty()){
            return new Page<SysUser>();
        }
        return page(user.getPage(), WrapperUtils.<SysUser>getLambdaQueryWrapper(user).in(SysUser::getId,userIdList));
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<SysUser> selectUnallocatedList(SysUser user)
    {
        List<String> userIdList = userRoleService.findListByRoleId(user.getRoleId()).stream().map(SysUserRole::getUserId).collect(Collectors.toList());
        LambdaQueryWrapper<SysUser> lqw = WrapperUtils.<SysUser>getLambdaQueryWrapper(user);
        if(!userIdList.isEmpty()){
            lqw.notIn(SysUser::getId,userIdList);
        }
        return page(user.getPage(),lqw);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名,email 邮箱,phonenumber 手机号码
     * @return 用户对象信息
     */
    public SysUser loadUser(String userName)
    {
        return getOne(Wrappers.<SysUser>lambdaQuery().and(w->w.eq(SysUser::getUserName,userName).or()
                .eq(SysUser::getEmail,userName).or().eq(SysUser::getPhonenumber,userName)).eq(SysUser::getStatus,"0"));
    }

    public SysUser findUserByUserName(String userName)
    {
        return getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName,userName).eq(SysUser::getStatus,"0"));
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    public String selectUserRoleGroup(String userId)
    {
        List<SysUserRole> urList = userRoleService.findListByUserId(userId);

        if (CollectionUtils.isEmpty(urList))
        {
            return StringUtils.EMPTY;
        }

        List<SysRole> list = roleService.listByIds(urList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().filter(r->"0".equals(r.getStatus())).map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userId 用户ID
     * @return 结果
     */
    public String selectUserPostGroup(String userId)
    {
        List<SysUserPost> upList = userPostService.findListByUserId(userId);
        if (CollectionUtils.isEmpty(upList))
        {
            return StringUtils.EMPTY;
        }

        List<SysPost> list = postService.listByIds(upList.stream().map(SysUserPost::getPostId).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().filter(p->"0".equals(p.getStatus())).map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean checkUserNameUnique(SysUser user)
    {
        SysUser info = getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName,user.getUserName()));
        if (StringUtils.isNotNull(info) && !info.getId().equals(user.getId()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    public boolean checkPhoneUnique(SysUser user)
    {
        SysUser info = getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhonenumber,user.getPhonenumber()));
        if (StringUtils.isNotNull(info) && !info.getId().equals(user.getId()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    public boolean checkEmailUnique(SysUser user)
    {
        SysUser info = getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getEmail,user.getEmail()));
        if (StringUtils.isNotNull(info) && !info.getId().equals(user.getId()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    public void checkUserDataScope(String userId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Transactional
    public void insertUser(SysUser user)
    {
        // 新增用户信息
        save(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean registerUser(SysUser user)
    {
        return save(user);
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Transactional
    public boolean updateUser(SysUser user)
    {
        String userId = user.getId();
        // 删除用户与角色关联
        userRoleService.removeByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostService.removeByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);

        return updateById(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Transactional
    public void insertUserAuth(String userId, String[] roleIds)
    {
        userRoleService.removeByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean updateUserStatus(SysUser user)
    {
        return update(Wrappers.<SysUser>lambdaUpdate().eq(SysUser::getId,user.getId()).set(SysUser::getStatus,user.getStatus()));
    }

    /**
     * 修改用户头像
     *
     * @param user 用户对象
     * @return 结果
     */
    public boolean updateUserAvatar(SysUser user)
    {
        return update(Wrappers.<SysUser>lambdaUpdate().eq(SysUser::getId,user.getId()).set(SysUser::getAvatar,user.getAvatar()));
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean resetPwd(SysUser user)
    {
        return update(Wrappers.<SysUser>lambdaUpdate().eq(SysUser::getId,user.getId()).set(SysUser::getPassword,user.getPassword()));
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        String[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (String postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostService.saveBatch(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(String userId, String[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (String roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleService.saveBatch(list);
        }
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的用户ID
     * @return 结果
     */
    @Transactional
    public boolean deleteUserByIds(String[] ids)
    {
        // 删除用户与角色关联
        userRoleService.removeByUserIds(ids);
        // 删除用户与岗位关联
        userPostService.removeByUserIds(ids);

        return removeByIds(Arrays.asList(ids));
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = findUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    save(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setId(u.getId());
                    user.setUpdateBy(operName);
                    updateById(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
